<template>
  <div
    class="interaction-section flex flex-col"
    :class="
      styleMode === 'cover'
        ? [
            'fixed bottom-0 left-0 w-full p-2 bg-opacity-50 text-white z-20 rounded-t-xl',
            imStore.messages.length > 0 ? 'bg-black' : ''
          ]
        : 'h-full'
    "
  >
    <!-- 标题 -->
    <div
      class="flex flex-col"
      v-if="isInteractionEnabled"
      :class="playerStore.isKeyboardVisible ? '' : 'flex-1'"
    >
      <!-- <h2
        v-if="styleMode !== 'cover'"
        class="text-center text-lg font-bold text-blue-500 mb-4"
      >
        课题互动
      </h2> -->
      <!-- 聊天消息区域 -->
      <div
        class="chat-box flex-1 overflow-y-auto pt-3"
        ref="chatBoxRef"
        :class="
          styleMode === 'cover'
            ? 'text-sm text-gray-300 mb-16'
            : ' border-gray-300'
        "
        v-if="!playerStore.isKeyboardVisible"
      >
        <!-- <div>
        <span>在线人数：{{ onlineMemberCount }}</span>
      </div> -->
        <div
          v-for="(message, index) in _messages"
          :key="index"
          class="chat-message mb-2"
          :class="styleMode === 'cover' ? 'mb-1' : ''"
          v-if="imStore.messages.length > 0"
        >
          <span
            class="rounded-full px-2 py-1 shadow-sm flex items-center gap-2"
            :class="styleMode === 'cover' ? '' : 'bg-white'"
          >
            <!-- 头像 -->
            <img
              v-if="message.avatar"
              :src="message.avatar"
              alt="avatar"
              class="w-6 h-6 rounded-full object-cover"
            />
            <span
              class="username font-bold"
              :class="styleMode === 'cover' ? 'text-cyan-400' : 'text-blue-600'"
            >
              {{ message.username }}
              <!-- 用户ID -->
              <span class="text-xs text-gray-400 ml-1">({{ message.id }})</span
              >：
            </span>
            <span
              class="content"
              :class="styleMode === 'cover' ? '' : 'text-gray-800'"
            >
              {{ message.content }}
            </span>
          </span>
        </div>
      </div>

      <!-- 输入框 -->
      <div
        class="chat-input mt-4 flex items-center gap-2"
        :class="[
          styleMode === 'cover' ? 'mt-2 bg-black bg-opacity-70 p-2' : '',
          !playerStore.isKeyboardVisible
            ? 'fixed bottom-0 left-0 w-full p-2 bg-opacity-50 text-white z-20 rounded-xl'
            : 'rounded-xl'
        ]"
      >
        <input
          v-model="newMessage"
          type="text"
          placeholder="说点什么吧..."
          class="flex-1 px-4 py-2 border rounded-lg focus:outline-none text-black"
          :class="
            styleMode === 'cover'
              ? 'bg-transparent border-none text-white placeholder-gray-400'
              : 'border-gray-300 focus:ring-2 focus:ring-blue-400'
          "
          @keyup.enter="sendMessage"
        />
        <button
          @click="sendMessage"
          class="px-4 py-2 rounded-lg transition"
          :class="
            styleMode === 'cover'
              ? 'bg-pink-500 text-white hover:bg-pink-600'
              : 'bg-pink-500 text-white hover:bg-pink-600'
          "
        >
          发送
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useTencentIM } from "@/utils/tencent-im";
import { ref, onUnmounted, onMounted, watch, nextTick } from "vue";
const imStore = useTencentIM();
useTencentIM();
interface Message {
  username: string;
  id: string;
  avatar: string;
  content: string;
}
// 接收样式风格参数
const props = defineProps({
  styleMode: {
    type: String,
    default: "" // 默认值为 cover
  },
  isInteractionEnabled: {
    type: Boolean,
    default: true
  }
});
// 聊天消息列表
import { computed } from "vue";
import InteractionMenu from "./interactionMenu.vue";
import { usePlayerStore } from "@/store/usePlayer";
const playerStore = usePlayerStore();
const chatBoxRef = ref<HTMLElement | null>(null);
const messageHeight = 40; // 估算每条消息高度（px）
const visibleCount = ref(5); // 默认显示5条

const updateVisibleCount = () => {
  if (chatBoxRef.value) {
    const height = chatBoxRef.value.clientHeight;
    visibleCount.value = Math.max(1, Math.floor(height / messageHeight));
  }
};

// 组件挂载后和窗口大小变化时更新
onMounted(() => {
  updateVisibleCount();
  window.addEventListener("resize", updateVisibleCount);
});
watch(chatBoxRef, updateVisibleCount);
watch(
  () => playerStore.isKeyboardVisible,
  () => nextTick(updateVisibleCount)
);

const _messages = computed<Message[]>(() =>
  imStore.messages
    .slice(props.styleMode == "cover" ? -5 : -visibleCount.value + 1)
    .map(msg => ({
      username: msg.nick,
      id: msg.from,
      avatar: msg.avatar,
      content: msg.payload.text
    }))
);

// 新消息输入框内容
const newMessage = ref<string>("");

// 发送消息
const sendMessage = (): void => {
  if (newMessage.value.trim() !== "") {
    imStore.sendMessageToGroup(newMessage.value.trim());
    newMessage.value = "";
  }
};

onUnmounted(() => {
  window.removeEventListener("resize", updateVisibleCount);
});
</script>

<style scoped>
/* Placeholder styling for input */
input::placeholder {
  color: #a0aec0; /* Tailwind's gray-400 */
}
</style>
